<script setup>
import {inject, onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {clearToken, confirmMessage, showMessage} from "../util/utils.js";

//定义router对象
let router = useRouter(); //调对象的方法
let route = useRoute(); //点对象的属性

//定义市场活动详情对象，初始值是空
let activityDetail = ref({
  ownerDO : {},
  createByDO : {},
  editByDO : {}
})

//页面dom元素渲染后执行回调函数钩子
onMounted(() => {
  // activityId参数要和router.js文件中配置的动态路由activityId名称要相同
  let id = route.params.activityId;
  //加载市场活动详情信息
  loadActivityDetail(id);
  //加载市场活动隶属备注信息
  loadActivityRemarkByPage(1);
})

const loadActivityDetail = (id) => {
  doGet('/api/activity/' + id, {}).then(resp => {
    if (resp.data.code === 200) {
      activityDetail.value = resp.data.data;
      if (!resp.data.data.ownerDO) {
        //避免后端没有查询到editByDO编辑人，前端读name字段的时候报null的错误
        activityDetail.value.ownerDO = {}
      }
      if (!resp.data.data.createByDO) {
        //避免后端没有查询到createByDO创建人，前端读name字段的时候报null的错误
        activityDetail.value.createByDO = {}
      }
      if (!resp.data.data.editByDO) {
        //避免后端没有查询到editByDO编辑人，前端读name字段的时候报null的错误
        activityDetail.value.editByDO = {}
      }
    } else {
      //提示一下
      showMessage('数据加载失败', 'error');
    }
  })
}

//定义活动备注信息对象（提交备注的时候使用），初始值是空
let activityRemarkQuery = ref({})

//返回函数
const goBack = () => {
  router.back();
}

//定义验证规则
let activityRemarkRules = ref({
  noteContent : [
    { required: true, message: '请输入活动备注', trigger: 'blur' },
    { min: 5, max : 255, message: '活动备注内容长度为5-255个字符', trigger: 'blur' },
  ]
})

//定义form中的ref属性对象
let activityRemarkFormRef = ref();

//注入刷新函数
let flushPage = inject('flush');

//提交活动备注
const activityRemarkSubmit = (formEl) => {
  if (!formEl) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formEl.validate((valid) => {
    if (valid) { //valid是true表示验证通过，否则没通过
      doPost('/api/activity/remark', {
        activityId : activityDetail.value.id, //活动id
        noteContent : activityRemarkQuery.value.noteContent,
      }).then(resp => {
        if (resp.data.code === 200) {
          showMessage('备注成功', 'success');
          //页面局部刷新
          flushPage();
        } else {
          showMessage('备注失败，原因：' + resp.data.msg, 'error');
        }
      })
    }
  })
}

//分页时总共有多少条数据
let total = ref(0)
//分页时每页显示多少条数据
let pageSize = ref(0)

//定义历史备注数组对象，初始值是空
let activityRemarkList = ref([{
  createByDO : {},
  editByDO : {}
}])

//加载市场活动隶属备注信息
const loadActivityRemarkByPage = (current) => {
  // activityId参数要和router.js文件中配置的动态路由activityId名称要相同
  let id = route.params.activityId;
  doGet('/api/activity/remarks', {
    current : current, //前面的current是参数名，后面的current是参数值
    activityId : id,
  }).then(resp => {
    if (resp.data.code === 200) {
      activityRemarkList.value = resp.data.data.list;
      total.value = resp.data.data.total;
      pageSize.value = resp.data.data.pageSize;
    } else {
      showMessage('数据加载失败', 'error');
    }
  })
}

//分页函数
const toPage = (current) => {
  loadActivityRemarkByPage(current);
}

//定义编辑活动柜备注的弹层是否要显示，true显示，false不显示
let activityRemarkVisible = ref(false)
//定义活动备注对象（编辑的时候使用）
let activityRemark = ref({})

//历史备注的编辑
const edit = (id) => {
  //把弹层先弹出来
  activityRemarkVisible.value = true;
  //根据id查询该备注的内容
  doGet('/api/activity/remark/' + id, {}).then(resp => {
    if (resp.data.code === 200) {
      activityRemark.value = resp.data.data;
    }
  })
}

//历史备注的删除
const del = (id) => {
  confirmMessage('您确定要删除此数据吗？').then(() => { //点确定就触发then函数
    doDelete('/api/activity/remark/' + id, {}).then(resp => {
      if (resp.data.code === 200) {
        showMessage('删除成功', 'success');
        //局部刷新页面
        flushPage();
      }
    })
  }).catch(() => { //点取消就触发catch函数
    showMessage('取消删除', 'warning')
  })
}

//编辑市场活动备注的验证规则
let activityRemarkEditRules = ref({
  noteContent : [
    { required: true, message: '请输入活动备注', trigger: 'blur' },
    { min: 5, max : 255, message: '活动备注内容长度为5-255个字符', trigger: 'blur' }
  ]
})

//定义form的ref属性对象
let activityRemarkEditFormRef = ref();
const editActivityRemarkSubmit = (formEl) => {
  if (!formEl) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formEl.validate((valid) => {
    if (valid) { //valid是true表示验证通过，否则没通过
      doPut('/api/activity/remark', {
        id : activityRemark.value.id, //活动备注id
        noteContent : activityRemark.value.noteContent
      }).then(resp => {
        if (resp.data.code === 200) {
          showMessage('备注编辑成功', 'success');
          //页面局部刷新
          flushPage();
        } else {
          showMessage('备注编辑失败，原因：' + resp.data.msg, 'error');
        }
      })
    }
  })
}
</script>

<template>
  <el-form ref="activityRemarkFormRef" :model="activityRemarkQuery" label-width="120px" :rules="activityRemarkRules">
    <el-form-item label="ID">
      <div class="divInfo">{{activityDetail.id}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="负责人">
      <div class="divInfo"> {{activityDetail.ownerDO.name}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="活动名称">
      <div class="divInfo">{{activityDetail.name}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="开始时间">
      <div class="divInfo">{{activityDetail.startTime}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="结束时间">
      <div class="divInfo">{{activityDetail.endTime}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="活动预算">
      <div class="divInfo">{{activityDetail.cost}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="活动描述">
      <div class="divInfo">{{activityDetail.description}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="创建时间">
      <div class="divInfo">{{activityDetail.createTime}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="创建人">
      <div class="divInfo">{{activityDetail.createByDO.name}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="编辑时间">
      <div class="divInfo">{{activityDetail.editTime}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="编辑人">
      <div class="divInfo">{{activityDetail.editByDO.name}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="活动备注" prop="noteContent">
      <el-input
          v-model="activityRemarkQuery.noteContent"
          maxlength="255"
          rows="8"
          placeholder="请输入活动备注"
          show-word-limit
          type="textarea"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="activityRemarkSubmit(activityRemarkFormRef)">提 交</el-button>
      <el-button type="success" plain @click="goBack">返 回</el-button>
    </el-form-item>

    <el-form-item label="历史备注">
      <el-table
          :data="activityRemarkList"
          style="width: 100%">
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column property="noteContent" label="备注内容"/>
        <el-table-column property="createTime" label="创建时间"/>
        <el-table-column property="createByDO.name" label="创建人"/>
        <el-table-column property="editTime" label="编辑时间"/>
        <el-table-column property="editByDO.name" label="编辑人"/>
        <el-table-column label="操作" width="90">
          <template #default="scope">
            <a href="javascript:void(0)" style="margin-right: 8px;" @click="edit(scope.row.id)">编辑</a>
            <a href="javascript:void(0)" @click="del(scope.row.id)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :background="true"
                     layout="prev, pager, next, jumper, ->, total"
                     :total="total"
                     :page-size="pageSize"
                     @current-change="toPage"/>
    </el-form-item>

  </el-form>

  <!--编辑市场活动历史备注的对话框蒙版弹层-->
  <el-dialog v-model="activityRemarkVisible" title="编辑活动备注" width="800" center>
    <el-form
        ref="activityRemarkEditFormRef"
        :model="activityRemark"
        :rules="activityRemarkEditRules"
        label-width="auto">
      <el-form-item label="备注内容" prop="noteContent">
        <el-input
            v-model="activityRemark.noteContent"
            maxlength="255"
            rows="8"
            placeholder="请输入活动备注"
            show-word-limit
            type="textarea"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="activityRemarkVisible = false">关 闭</el-button>
        <el-button type="primary" @click="editActivityRemarkSubmit(activityRemarkEditFormRef)">提 交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.divInfo {
  background: azure;
  width: 100%;
  margin-left: 10px;
  padding-left: 10px;
}
.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>